using System.Collections.Generic;
using System.Linq;
using Data;
using Model.Entities;
using Nethouse.Lib.Mvp;

namespace Business.EditOrder
{
    public class EditOrderPresenter : Presenter<IEditOrderView>
    {
        private readonly IRepository<Company> companyRepository;
        private readonly IRepository<Order> orderRepository;

        public EditOrderPresenter(IRepository<Company> companyRepository, IRepository<Order> orderRepository)
        {
            this.companyRepository = companyRepository;
            this.orderRepository = orderRepository;
        }

        protected override void ViewCreated()
        {
            View.CompanyList = companyRepository.All().ToList();
            View.OrderList = new List<Order>();
        }

        protected override void ViewLoaded()
        {
            View.CompanyChanged += ViewOnCompanyChanged;
            View.OrderChanged += ViewOnOrderChanged;
        }

        private void ViewOnCompanyChanged()
        {
            if (View.CurrentCompany > 0)
            {
                Company currentCompany = companyRepository.GetById(View.CurrentCompany);
                View.OrderList = currentCompany.OrderList;
            }
            else
            {
                View.OrderList = new List<Order>();
            }

            ViewOnOrderChanged();
        }

        private void ViewOnOrderChanged()
        {
            if (View.CurrentOrder > 0)
            {
                Order currentOrder = orderRepository.GetById(View.CurrentOrder);

                View.OrderNumber = currentOrder.OrderNumber;
                View.OrderRowList = currentOrder.OrderRowList;
            }
            else
            {
                View.OrderNumber = string.Empty;
                View.OrderRowList = new List<OrderRow>();
            }
        }
    }
}
